package top.zackyoung.demo.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import top.zackyoung.demo.dao.UserRepository;
import top.zackyoung.demo.entity.User;
import top.zackyoung.demo.service.JpaService;

import java.util.stream.Stream;

/**
 * @author: ZackYoung
 * @time: 2020/9/18
 */
@Service
@CacheConfig(cacheNames = "userService")
public class JpaServiceImpl implements JpaService {

    @Autowired
    private UserRepository userRepository;

    @Override
    public String  add1(User user) {
        try {
            userRepository.save(user);
            return "成功";
        } catch (Exception e) {
            return "应不可抗拒原因而失败";
        }
    }

    @Override
    public int add2(Long id, String name) {
        return userRepository.add(id,name);
    }

    @Override
    public int delete(Long id) {
        return userRepository.deleteUserById(id);
    }


    /**
     * 执行该函数时，将清除以 userService 的缓存，【cacheNames = "userService"】<br>
     * 也可指定清除的key 【@CacheEvict(value="abc")】
     */
    @Override
    @CacheEvict(value = "getAllUsers")
    public Iterable<User> getAllUsers() {
        return userRepository.findAll();
    }

    @Override
    public User getByNameUser(String name) {
        return userRepository.findByUserName(name);
    }

    @Override
    public int updateByUserId(Long id, String name) {
        return userRepository.updateByUserId(id, name);
    }

    @Override
    public Stream<User> findAllOrder(Long roleId, Integer page) {
        //Jpa 分页查询
        //通过订单日期进行排序，orderdate 是OrderBean 中的变量，不是数据库中的字段（*）
        Sort sort = Sort.by(Sort.Direction.DESC,"userName");

        // page 从 0 开始 ，3 是指每个page的大小，这个意思是按照订单日期排序分页查询，每次查询三个数据
        Pageable pageable = PageRequest.of(page,2,sort);
        return userRepository.findByRoleId(roleId,pageable).get();
    }
}
